
Module Optfile

  ! Handle na .opt file

  implicit none

  integer, parameter :: opt_ok = 0, opt_end = -1, opt_err = 1

contains

  function opt_open(n,name,i)

    implicit none

    integer, intent(in) :: n
    integer, intent(out) :: i
    character(len=*), intent(in) :: name
    logical :: opt_open 

    open(n,file=name,status='old',iostat=i)

    opt_open = i == 0

  end function opt_open


  subroutine opt_read(n,key,value,i)

    implicit none

    integer, intent(in) :: n
    integer, intent(out) :: i
    character(len=*), intent(out) :: key,value
    character(len=81) :: line
    integer :: c,ir

    do 
       read(n,'(A)',iostat=i,err=666,end=99) line

       c = index(line,'!') + index(line,'#')
       if( c > 0 ) then
          c = c - 1
       else
          c = len_trim(line)
       endif
       ir = index(line(:c),'=')
       if( ir > 0 ) then
          key = adjustl(line(:ir-1))
          value = adjustl(line(ir+1:))
          i = opt_ok
          return
       endif
    enddo

99  continue
    i = opt_end
    return

666 continue
    i = opt_err

  end subroutine opt_read

  subroutine opt_close(n)

    implicit none
    integer, intent(in) :: n

    close(n)

  end subroutine opt_close

end Module Optfile
